package sunyu.tools.redis;

import org.nutz.lang.Lang;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;

@Component
public class JedisTools {

    private static final Logger logger = LoggerFactory.getLogger(Thread.currentThread().getClass());

    @Resource(name = "jedisPool")
    private JedisPool jedisPool;

    private Jedis getJedis() {
        return jedisPool.getResource();
    }

    public <T> T execute(JedisCallback<T> action) {
        logger.debug("从jedisPool中获取jedis");
        Jedis jedis = getJedis();
        try {
            logger.debug("执行回调");
            T result = action.callback(jedis);
            return result;
        } catch (Throwable throwable) {
            throw Lang.wrapThrow(throwable);
        } finally {
            logger.debug("释放jedis");
            jedis.close();
        }
    }

}